$(() => {
    load();
});
const reLoad = () => {
    $('#exampleTable').bootstrapTable('refresh')
}

const setOneAndTwo = async (title, title1, id, value1, value2,status) => {
    //获取数据
    let myOption = '', myOption1 = '',
        select1 = id ? `<select name="interest" id="myselect1" lay-search="" lay-verify="required" lay-filter="aihao" disabled>`
            : `<select name="interest" id="myselect1" lay-search="" lay-verify="required" lay-filter="aihao">`
    const oneAndTwoData = await getOneAndTwo(status)
    if (id) {
        myOption += ` <option value="${id}" selected>${value1}</option>`
    }
    if (id) {
        myOption1 += ` <option value="${id}" selected>${value2}</option>`
    }
    for (let i = 0; i < oneAndTwoData?.num1.length; i++) {
        if (oneAndTwoData?.num1 !== []) {
            if (id && value1 == oneAndTwoData?.num1[i].num1s) {
                myOption += ` <option value="${oneAndTwoData?.num1[i].id}" selected>${oneAndTwoData?.num1[i].num1}</option>`
            } else if (oneAndTwoData?.num1[i].num1s != null) {
                myOption += ` <option value="${oneAndTwoData?.num1[i].id}">${oneAndTwoData?.num1[i].num1}</option>`
            }
        }
    }
    for (let j = 0; j < oneAndTwoData.num2.length; j++) {
        if (oneAndTwoData.num2 !== []) {
            if (id && value2 == oneAndTwoData?.num2[j].num2) {
                myOption1 += ` <option value="${oneAndTwoData.num2[j].id}" selected>${oneAndTwoData.num2[j].num2}</option>`
            } else if (oneAndTwoData?.num2[j].num2 != null) {
                myOption1 += ` <option value="${oneAndTwoData.num2[j].id}">${oneAndTwoData.num2[j].num2}</option>`
            }
        }

    }

    //一二
    const index = layer.open({
        type: 1,
        area: ['500px', '500px'],
        title: title,
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content: `
<form class="layui-form layui-form-pane" style="width: 100%;height: 100%;padding: 10px;" id="myForm">

  <div class="layui-form-item">
        <label class="layui-form-label" style="width:auto;border: 0;">${title1}</label>
  </div>
    <div class="layui-form-item">
    <label class="layui-form-label" style="width:auto;border: 0;">一次加密号</label>
    <div class="layui-input-inline" style="width: calc(100% - 140px);">
      ${select1}
        <option value="">请选择一次加密序号</option>
       ${myOption}
      </select>
    </div>
  </div>
    <div class="layui-form-item">
    <label class="layui-form-label" style="width:auto;border: 0;">二次加密号</label>
    <div class="layui-input-inline" style="width: calc(100% - 140px);">
      <select name="interest1" id="myselect2" lay-search="" lay-verify="required" lay-filter="aihao">
        <option value="">请选择与一次加密号对应的二次加密号</option>
       ${myOption1}
      </select>
    </div>
  </div>
  <div class="layui-form-item" style="display: flex;    justify-content: center;">
    <button class="layui-btn" type="button"  lay-submit lay-filter="layedit-code-yes">提交</button>
  </div>
</form>
                `,
        success: (layero, index) => {
            layui.use(['form'], () => {
                setTimeout(()=>{
                    selectInput('myselect1',layero)
                    selectInput('myselect2',layero)
                },50)

                var form = layui.form;
                form.render('select');
                form.on('submit(layedit-code-yes)', (data) => {
                    const mydata = data.field
                    const reqData = {
                        id: mydata.interest,
                        isScore:id?1:0
                    }
                    //根据id获取数据
                    oneAndTwoData.num1.forEach((item) => {
                        if (item.id == mydata.interest) {
                            reqData.num1s = item.num1
                        }
                    })
                    oneAndTwoData.num2.forEach((item) => {
                        if (item.id == mydata.interest1) {
                            reqData.num2s = item.num2
                        }
                    })
                    console.log('提交数据', oneAndTwoData, mydata, reqData)
                    if (id) {
                        if (!reqData.num1s) {
                            reqData.num1s = value1
                        }
                        if (!reqData.num2s) {
                            reqData.num2s = value2
                        }
                    }
                    console.log('提交数据', reqData)
                    //修改
                    $.ajax({
                        type: 'post',
                        data: JSON.stringify({
                            ...reqData,
                            field:"B4"
                        }),
                        contentType: 'application/json',
                        url: '/updateNum1BindNum2Decrypt',
                        success: function (r) {
                            if (r.code == 0) {
                                layer.msg(r.msg);
                                layer.close(index)
                                reLoad();
                            } else {
                                layer.msg(r.msg);
                            }
                        }
                    });

                });
            })


        }
    });
}

const getOneAndTwo = (status) => {
    return new Promise((resolve, reject) => {
        let pData = {
            current: 1,
            size: 10000,
            field:"B4",
            status
        }
        $.ajax({
            type: 'get',
            data:  pData,
            contentType: 'application/json',
            url: '/getBindNum',
            success: function (r) {
                if (r.code == 0) {
                    resolve(r.data)
                } else {
                    layer.msg(r.msg);
                    reject(r)
                }
            }
        });
    })
}

const EntryScore = async (item = null) => {
    console.log('=====>>录入分数>', item)
    setOneAndTwo('信息录入', '请仔细核对信息', '', '', '','0')
}


const derive = () => {
    layer.confirm(`是否导出婴幼儿早期发展赛场一次加密与二次加密匹配信息？`, {
        btn1: function (index) {
            window.location.href = '/downloadImportDecrypt?field=B4&type=3';
            layer.close(index)
        }
    });
}

const edit = (mydata) => {
    console.log('=====>>修改>', mydata)
    setOneAndTwo('信息录入', '请仔细核对信息', mydata.id, mydata.num1s, mydata.num2s,'1')
}

const columns = [
    {
        field: 'num1s',
        title: '一次加密号',
        width: '105px'
    },
    {
        field: 'num2s',
        title: '二次加密号',
        width: '105px'
    },
    {
        title: '操作',
        field: 'id',
        align: 'center',
        // width:'50px',
        formatter: function (value, row, index) {
            return row.statuss==='1'?'':`          <a style="color: #18a689" class="${s_edit_h}" href="#" mce_href="#" title="修改" onclick="edit(${JSON.stringify(row).replace(/\"/g, "'")})">修改</a>
                                                                          <a style="color: red" class="${s_reset_h}" href="#" mce_href="#" title="重置" onclick="remove('${row.id}','${row.field}')">重置</a>`;
        },
        width: '230px'
    }
]
columns.forEach(item => {
    item.align = 'center'
    item.valign='middle'
})
function load() {
    $('#exampleTable')
        .bootstrapTable(
            {
                method: 'post', // 服务器数据的请求方式 get or post
                url: '/getDecrypt', // 服务器数据的加载地址
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: true, // 设置为true会有隔行变色效果
                dataType: "json", // 服务器返回的数据类型
                pagination: true, // 设置为true会在底部显示分页条
                singleSelect: false, // 设置为true将禁止多选
                // contentType : "application/x-www-form-urlencoded",
                // //发送到服务器的数据编码类型
                pageSize: 10, // 如果设置了分页，每页数据条数
                pageNumber: 1, // 如果设置了分布，首页页码
                //search : true, // 是否显示搜索框
                showColumns: false, // 是否显示内容下拉框（选择显示的列）
                sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
                queryParamsType: "",
                queryParams: function (params) {
                    console.log('params', params)
                    return {
                        current: params.pageNumber,
                        size: params.pageSize,
                        field:"B4"
                    };
                },
                responseHandler: function (res) {
                    if (res.code !== '0') {
                        layer.msg(res.msg);
                        return false
                    }
                    return {
                        "rows": res.data.records,
                        ...res.data
                    };
                },
                columns
            });
}

function remove(id,field) {
    layer.confirm('是否重置？', {
        btn: ['确定', '取消'], // 按钮
        title: '提示', // 标题
        closeBtn: 0, // 关闭按钮，0代表不显示
        shadeClose: true, // 是否点击遮罩关闭
    },async function(index){
        // 确定按钮的回调函数
        await resetDate(id,field)
        layer.close(index); // 关闭确认框
        // 执行删除操作或其他操作
    }, function(index){
        layer.close(index); // 关闭确认框
    });

}

function resetDate(id,field) {
    $.ajax({
        type: 'get',
        url: `/resetNum1BindNum2Decrypt?id=${id}&field=${field}`,
        success: function (r) {
            if (r.code === '0') {
                layer.msg('重置成功');
                reLoad()
            } else {
                layer.msg(r.msg);
            }
        }
    });
}